<?php

/**
 * 	frontend communication with mail chimp
 *	based on the mailchimp api class, provided by mailchimp itself
 *
 *	@author 	pieter van peteghem <pieter@onedotonly.be>
 *	@date		30 march 2011
 */
 
class SocialMailchimp extends MOD {


	/**
	 *	constructor
	 *	
	 *	add module vars and reference (multiple modules on 1 page are possible)	
	 *	@param		array ($vars)
	 */
	 
	function __construct( $vars ) {
		$this->_addvars( $vars );
		$this->_ref();
	}



	/**
	 * 	define output
	 *	this is the base for rendering the stars at the frontend
	 */
	 
	function output () {
				
		if( $this->action )
			$result = $this->{ "filter_" . $this->action }();

		$this->addclass( $this->action );
		
		if ( $result && is_array( $result ))
			$result = '<ul>' . implode( "\n", $result ) . '</ul>';
			
		if( $result )	
			return $this->parse( $result ) . $this->render_js();
		
	}
	
	
	
	/**
	 *	basic subscriptions
	 */
	 
	function filter_basic() {
		global $DB;
		
		$return	= '<form method="post" action="">';
		$return.= '<input type="text" placeholder="e-mail" name="mail" />';
		$return.= '<input type="text" placeholder="naam" name="fname" />';
		$return.= '<input type="button" value="send" />';
		$return.= '</form>';
		
	    $this->js = "
	    	mod = new SocialMailchimp( " . json_encode( $this->vars ) . " );
	    	mod.subscribe();
	    ";
	
	    return $return;
	
	}
	
	
	function ajax_subscribe() {
		global $Request;
		
		require_once ROOT . 'engine/ext/mailchimp/MCAPI.class.php';
		$go = false;
		
		$vars	= $this->vars->vars;
		unset( $this->vars->vars );
		
		if( !empty( $this->vars->mail ) && eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $this->vars->mail )) {
			$mail	= preg_replace( "/[^\w\s\.\-\@]/", "", $this->vars->mail );
			$go 	= true;
		}	
		if( !empty( $this->vars->fname )) {
			$name	= $this->vars->fname;
			$go = true;
		}
		if( $go ) {
			$api = new MCAPI( engine_get( 'social.mailchimp' ) );
			$api->listSubscribe( $vars->listid, $mail, array( 'FNAME' => $name ), 'html', false, false, true, false );
 
			if ( $api->errorCode )
				$return = "<span class='error'>" . translate( 'Foutje...' ) . "</span>";
			else
				$return = "<span class='subscribed'>" . translate( 'U bent ingeschreven' ) . "</span>";
		} else {
			$return = "<span class='subscribed'>" . translate( 'Foutje...' ) . "</span>";
		}
		
		echo $return;
		
	}
}